package cn.com.anypay.manager.miaoma.miaomaarticle;

import cn.com.anypay.manager.common.enums.ResultCode;
import cn.com.anypay.manager.common.response.ApiResponse;
import cn.com.anypay.manager.miaoma.miaomaarticle.auto.AutoMiaomaArticleServiceImpl;
import cn.com.anypay.manager.miaoma.miaomaarticle.mapper.MiaomaArticleMapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class MiaomaArticleService extends AutoMiaomaArticleServiceImpl {

    private static final Logger log = LoggerFactory.getLogger(MiaomaArticleService.class);

    @Autowired
    private MiaomaArticleMapper miaomaArticleMapper;

    public ApiResponse<List<MiaomaArticleEntity>> getPublishedArticleList() {
        log.info("获取已发布文章列表");
        QueryWrapper<MiaomaArticleEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("status", "published").orderByDesc("created_time");
        List<MiaomaArticleEntity> articles = miaomaArticleMapper.selectList(queryWrapper);
        log.debug("查询到已发布文章数量: {}", articles.size());
        return ApiResponse.success(articles);
    }

    public ApiResponse<MiaomaArticleEntity> getArticleInfo(Long id) {
        log.info("获取文章详情, id={}", id);
        MiaomaArticleEntity article = miaomaArticleMapper.selectById(id);
        if (article == null) {
            log.warn("未找到id={}的文章", id);
            return ApiResponse.fail(ResultCode.CUSTOM_FAIL, "文章不存在");
        }
        return ApiResponse.success(article);
    }

    public ApiResponse<String> downloadArticle(Long id) {
        log.info("下载文章, id={}", id);
        MiaomaArticleEntity article = miaomaArticleMapper.selectById(id);
        if (article == null) {
            log.warn("未找到id={}的文章，无法下载", id);
            return ApiResponse.fail(ResultCode.NOT_FOUND, "文章不存在");
        }

        // 构建Markdown格式的文章内容
        String content = "# " + article.getTitle() + "\n\n" +
                "作者: " + article.getAuthor() + "\n" +
                "创建时间: " + article.getCreatedTime() + "\n\n" +
                (article.getContent() != null ? article.getContent() : "");
        log.debug("文章下载内容生成成功, id={}", id);
        return ApiResponse.success(content);
    }
}